package cn.calm.transaction;

import java.lang.reflect.Method;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import net.sf.cglib.proxy.InvocationHandler;
import net.sf.cglib.proxy.Proxy;

import org.apache.struts2.osgi.proxy.OsgiObjectWrap;

import cn.calm.commons.dao.transaction.Transaction;
import cn.calm.commons.service.IBaseService;

public class TransactionOsgiObjectWrap implements OsgiObjectWrap,InvocationHandler  {
	private Object proxyedObject;

	@Override
	public Object wrap(Object obj) {
		this.proxyedObject = obj;  
        //取得代理对象  
        return Proxy.newProxyInstance(proxyedObject.getClass().getClassLoader(),  
        		proxyedObject.getClass().getInterfaces(), this);   //要绑定接口(这是一个缺陷，cglib弥补了这一
	}

	@SuppressWarnings("rawtypes")
	public Object invoke(Object object, Method method, Object[] arguments)
			throws Throwable {
		Transaction tran= method.getAnnotation(Transaction.class);
		if(tran==null){
			return method.invoke(proxyedObject, arguments);
		}
		if(proxyedObject instanceof IBaseService){
			IBaseService service =(IBaseService) proxyedObject;
			EntityManager em=service.getBaseDao().getSession();
			EntityTransaction transc=em.getTransaction();
			try{
				if(transc!=null){
					transc.begin();
				}
				Object result= method.invoke(proxyedObject, arguments);
				if(transc!=null){
					transc.commit();
				}
				return result;
			}catch (Exception e) {
				if(transc!=null){
					transc.rollback();
				}
				throw e;
			}
		}
		return method.invoke(proxyedObject, arguments);
	}
}
